package com.book.dao.impl;

import com.book.dao.StudentDao;
import com.book.domain.Book;
import com.book.domain.Student;
import com.book.utils.JDBCUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class StudentDaoImpl implements StudentDao {
    @Override
    public Student login(String username, String password) {
        Connection conn = null;
        PreparedStatement pstat = null;
        ResultSet rs = null;
        Student student = null;
        String sql = "select * from student where username=? and password=?";
        try {
            JDBCUtil.registerDriver();
            conn = JDBCUtil.getConnection();
            pstat = conn.prepareStatement(sql);
            pstat.setString(1,username);
            pstat.setString(2,password);
            rs = pstat.executeQuery();
            while (rs.next()) {
                int id = rs.getInt("id");
                String name = rs.getString("name");
                String sex = rs.getString("sex");
                String stuClass = rs.getString("stuClass");
                int age = rs.getInt("age");
                String username1 = rs.getString("username");
                String password1 = rs.getString("password");
                student = new Student(id, name, sex, stuClass, age, username1, password1);
            }

        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            JDBCUtil.realeaseAll(rs, pstat, conn);
        }
        return student;
    }

    @Override
    public List<Book> findBook() {
        Connection conn = null;
        PreparedStatement pstat = null;
        ResultSet rs = null;
        Book book = null;
        List<Book> books = new ArrayList<>();
        String sql = "select * from book ";
        try {
            JDBCUtil.registerDriver();
            conn = JDBCUtil.getConnection();
            pstat = conn.prepareStatement(sql);
            rs = pstat.executeQuery();
            while (rs.next()) {
                int bookId = rs.getInt("bookId");
                String bookName = rs.getString("bookName");
                String bookAuthor = rs.getString("bookAuthor");
                String bookType = rs.getString("bookType");
                int amount = rs.getInt("amount");
                int number = rs.getInt("number");
                book = new Book(bookId, bookName, bookAuthor, bookType, amount, number);
                books.add(book);
            }

        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            JDBCUtil.realeaseAll(rs, pstat, conn);
        }
        return books;
    }

}
